package com.aijk.web.admin.controller.medical;

import com.aijk.commons.mijo.utils.PojoUtil;
import com.aijk.commons.utils.Collections3;
import com.aijk.commons.utils.Utils;
import com.aijk.medical.api.BasRegionApi;
import com.aijk.medical.model.BasRegion;
import com.aijk.medical.model.qo.BasRegionQo;
import com.aijk.web.admin.RetMsg;
import com.aijk.web.admin.controller.BaseController;
import com.aijk.web.admin.entity.FdStatisticBaseVo;
import com.aijk.web.admin.entity.ResidentTypeEnum;
import com.aijk.web.admin.utils.DataTableUtil;
import com.aijk.web.admin.utils.DateUtil;
import com.aijk.web.admin.utils.ExcelUtils;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.lifesea.commons.exception.ErrorCodeException;
import com.lifesea.familydoctor.api.FdStatisticBaseApi;
import com.lifesea.familydoctor.api.FdStatisticsApi;
import com.lifesea.familydoctor.model.FdStatisticBase;
import com.lifesea.familydoctor.model.ext.FdStatisticsGroup;
import com.lifesea.familydoctor.model.ext.FdStatisticsType;
import com.lifesea.familydoctor.model.qo.FdStatisticBaseQo;
import com.lifesea.familydoctor.model.qo.FdStatisticsGroupQo;
import com.lifesea.familydoctor.model.qo.FdStatisticsTypeQo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


@Controller
@RequestMapping("/medical/base/statistic")
public class FdStatisticBaseController extends BaseController {

    @Autowired
    private FdStatisticsApi fdStatisticsApi;

    @Autowired
    private FdStatisticBaseApi fdStatisticBaseApi;

    @Autowired
    private BasRegionApi basRegionApi;


    @RequestMapping(value = "listStreet", method = RequestMethod.GET)
    public String listStreet(Model model) {
        return "/medical/statistics/list_street";
    }

    /**
     * 签约工作量-街道
     */
    @RequestMapping(value = "listStreet", method = RequestMethod.POST)
    @ResponseBody
    public RetMsg listStreet(@RequestParam HashMap skey, @RequestParam(value = "draw", defaultValue = "1") Integer draw) {
        Long iTotalRecords;
        DataTableUtil.FormatOptions(skey);
        FdStatisticsGroupQo qo = DataTableUtil.fillQo(skey,FdStatisticsGroupQo.class);
        draw += 1;
        PageInfo<FdStatisticsGroup> page = fdStatisticsApi.calculateStreetGroup(qo);
        List<FdStatisticsGroup> groupList = page.getList();
        List<HashMap> resultList = new ArrayList<>();
        HashMap totalresult = new HashMap();
        Integer totalTeamNum = 0;
        Integer totalPregnantGroup  = 0;
        Integer totalChildrenGroup  = 0;
        Integer totalAgedGroup = 0;
        Integer totalHypertensionGroup  = 0;
        Integer totalDiabeticGroup = 0;
        Integer totalPsychoticGroup = 0;
        Integer totalTuberculosisGroup = 0;
        Integer totalDisabledGroup = 0;
        Integer totalFamilyPlanSpecialGroup = 0;
        Integer totalNoKeyGroup = 0;
        Integer totalRecordCardGroup = 0;
        Integer totalAllowancesGroup = 0;
        Integer totalKeyGroup = 0;

        try {
            for(FdStatisticsGroup group : groupList){
                HashMap result = new HashMap();
                result.put("streetId", group.getStreetId());
                result.put("streetName", group.getStreetName());
                result.put("teamNum", group.getTeamNum());
                Integer totalNum = 0;
                totalTeamNum = totalTeamNum + group.getTeamNum();
                for(FdStatisticsType type : group.getTypeNum()) {
                    result.put(ResidentTypeEnum.getNameByType(type.getType()), type.getNum());
                    if("pregnantGroup".equals(ResidentTypeEnum.getNameByType(type.getType()))){
                        totalPregnantGroup = totalPregnantGroup + type.getNum();
                        totalNum = totalNum +  type.getNum();
                    };
                    if("childrenGroup".equals(ResidentTypeEnum.getNameByType(type.getType()))){
                        totalChildrenGroup = totalChildrenGroup + type.getNum();
                        totalNum = totalNum +  type.getNum();
                    };
                    if("agedGroup".equals(ResidentTypeEnum.getNameByType(type.getType()))){
                        totalAgedGroup = totalAgedGroup + type.getNum();
                        totalNum = totalNum +  type.getNum();
                    };
                    if("hypertensionGroup".equals(ResidentTypeEnum.getNameByType(type.getType()))){
                        totalHypertensionGroup = totalHypertensionGroup + type.getNum();
                        totalNum = totalNum +  type.getNum();
                    };
                    if("diabeticGroup".equals(ResidentTypeEnum.getNameByType(type.getType()))){
                        totalDiabeticGroup = totalDiabeticGroup + type.getNum();
                        totalNum = totalNum +  type.getNum();
                    };
                    if("psychoticGroup".equals(ResidentTypeEnum.getNameByType(type.getType()))){
                        totalPsychoticGroup = totalPsychoticGroup + type.getNum();
                        totalNum = totalNum +  type.getNum();
                    };
                    if("tuberculosisGroup".equals(ResidentTypeEnum.getNameByType(type.getType()))){
                        totalTuberculosisGroup = totalTuberculosisGroup + type.getNum();
                        totalNum = totalNum +  type.getNum();
                    };
                    if("disabledGroup".equals(ResidentTypeEnum.getNameByType(type.getType()))){
                        totalDisabledGroup = totalDisabledGroup + type.getNum();
                        totalNum = totalNum +  type.getNum();
                    };
                    if("familyPlanSpecialGroup".equals(ResidentTypeEnum.getNameByType(type.getType()))){
                        totalFamilyPlanSpecialGroup = totalFamilyPlanSpecialGroup + type.getNum();
                        totalNum = totalNum +  type.getNum();
                    };
                    if("noKeyGroup".equals(ResidentTypeEnum.getNameByType(type.getType()))){
                        totalNoKeyGroup = totalNoKeyGroup + type.getNum();
                    };
                    if("recordCardGroup".equals(ResidentTypeEnum.getNameByType(type.getType()))){
                        totalRecordCardGroup = totalRecordCardGroup + type.getNum();
                        totalNum = totalNum +  type.getNum();
                    };
                    if("allowancesGroup".equals(ResidentTypeEnum.getNameByType(type.getType()))){
                        totalAllowancesGroup = totalAllowancesGroup + type.getNum();
                        totalNum = totalNum +  type.getNum();
                    };

                }
                result.put("totalNum", totalNum);
                //重点人群
                FdStatisticsTypeQo typeQo = PojoUtil.convert(qo, FdStatisticsTypeQo.class);
                typeQo.setStreetId(group.getStreetId());
                typeQo.setTeamId(null);
                typeQo.setReviewerUid(null);
                FdStatisticsType keyGroup = fdStatisticsApi.calculateKeyGroup(typeQo);
                if(keyGroup != null && keyGroup.getNum() > 0){
                    result.put("keyGroup", keyGroup.getNum());
                    totalKeyGroup = totalKeyGroup+ keyGroup.getNum();
                }else{
                    result.put("keyGroup", 0);
                }
                resultList.add(result);
            }
            Integer totalTotalNum = totalPregnantGroup + totalChildrenGroup + totalAgedGroup + totalHypertensionGroup + totalDiabeticGroup + totalPsychoticGroup + totalTuberculosisGroup + totalDisabledGroup + totalFamilyPlanSpecialGroup + totalRecordCardGroup + totalAllowancesGroup;
            totalresult.put("streetId", 0);
            totalresult.put("streetName", "合计");
            totalresult.put("teamNum", totalTeamNum);
            totalresult.put("pregnantGroup", totalPregnantGroup);
            totalresult.put("childrenGroup", totalChildrenGroup);
            totalresult.put("agedGroup", totalAgedGroup);
            totalresult.put("hypertensionGroup", totalHypertensionGroup);
            totalresult.put("diabeticGroup", totalDiabeticGroup);
            totalresult.put("psychoticGroup", totalPsychoticGroup);
            totalresult.put("tuberculosisGroup", totalTuberculosisGroup);
            totalresult.put("disabledGroup", totalDisabledGroup);
            totalresult.put("familyPlanSpecialGroup", totalFamilyPlanSpecialGroup);
            totalresult.put("noKeyGroup", totalNoKeyGroup);
            totalresult.put("recordCardGroup", totalRecordCardGroup);
            totalresult.put("allowancesGroup", totalAllowancesGroup);
            totalresult.put("totalNum", totalTotalNum);
            totalresult.put("keyGroup", totalKeyGroup);
            resultList.add(totalresult);
        } catch (Exception e) {
            e.printStackTrace();
        }
        RetMsg retMsg = new RetMsg();
        iTotalRecords = page.getTotal()+1;
        retMsg.put("data", resultList);
        retMsg.put("draw", draw);
        retMsg.put("recordsTotal", iTotalRecords);
        retMsg.put("recordsFiltered", iTotalRecords);
        return retMsg;
    }

    @RequestMapping(value = "listTeam", method = RequestMethod.GET)
    public String listTeam(Model model,Integer streetId) {
        model.addAttribute("streetId",streetId);
        return "/medical/statistics/list_team";
    }
    /*
    * 签约工作量-团队
     */
    @RequestMapping(value = "listTeam", method = RequestMethod.POST)
    @ResponseBody
    public  RetMsg listTeam(@RequestParam HashMap skey, @RequestParam(value = "draw", defaultValue = "1") Integer draw) {
        Long iTotalRecords;
        DataTableUtil.FormatOptions(skey);
        FdStatisticsGroupQo qo = DataTableUtil.fillQo(skey,FdStatisticsGroupQo.class);
        draw += 1;
        PageInfo<FdStatisticsGroup> page = fdStatisticsApi.calculateTeamGroup(qo);
        List<FdStatisticsGroup> groupList = page.getList();
        List<HashMap> resultList = new ArrayList<>();
        try {
            for(FdStatisticsGroup group : groupList){
                HashMap result = new HashMap();
                result.put("streetId", qo.getStreetId());
                result.put("teamId", group.getTeamId());
                result.put("teamName", group.getTeamName());
                for(FdStatisticsType type : group.getTypeNum()) {
                    result.put(ResidentTypeEnum.getNameByType(type.getType()), type.getNum());

                }
                //重点人群
                FdStatisticsTypeQo typeQo = PojoUtil.convert(qo, FdStatisticsTypeQo.class);
                typeQo.setStreetId(group.getStreetId());
                typeQo.setTeamId(null);
                typeQo.setReviewerUid(null);
                FdStatisticsType keyGroup = fdStatisticsApi.calculateKeyGroup(typeQo);
                if(keyGroup != null && keyGroup.getNum() > 0){
                    result.put("keyGroup", keyGroup.getNum());
                }else{
                    result.put("keyGroup", 0);
                }
                resultList.add(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        RetMsg retMsg = new RetMsg();
        iTotalRecords = page.getTotal();
        retMsg.put("data", resultList);
        retMsg.put("draw", draw);
        retMsg.put("recordsTotal", iTotalRecords);
        retMsg.put("recordsFiltered", iTotalRecords);
        return retMsg;
    }

    @RequestMapping(value = "listMember", method = RequestMethod.GET)
    public String listMember(Model model,Integer teamId,Integer streetId) {
        model.addAttribute("streetId",streetId);
        model.addAttribute("teamId",teamId);
        return "/medical/statistics/list_member";
    }

    /*
    * 签约工作量-成员
    */
    @RequestMapping(value = "listMember", method = RequestMethod.POST)
    public @ResponseBody RetMsg listMember(@RequestParam HashMap skey, @RequestParam(value = "draw", defaultValue = "1") Integer draw) {
        Long iTotalRecords;
        DataTableUtil.FormatOptions(skey);
        FdStatisticsGroupQo qo = DataTableUtil.fillQo(skey,FdStatisticsGroupQo.class);
        draw += 1;
        PageInfo<FdStatisticsGroup> page = fdStatisticsApi.calculateMemberGroup(qo);
        List<FdStatisticsGroup> groupList = page.getList();
        List<HashMap> resultList = new ArrayList<>();
        try {
            for(FdStatisticsGroup group : groupList){
                HashMap result = new HashMap();
                result.put("memberName", group.getServantName());
                for(FdStatisticsType type : group.getTypeNum()) {
                    result.put(ResidentTypeEnum.getNameByType(type.getType()), type.getNum());
                }
                //重点人群
                FdStatisticsTypeQo typeQo = PojoUtil.convert(qo, FdStatisticsTypeQo.class);
                typeQo.setStreetId(group.getStreetId());
                typeQo.setTeamId(null);
                typeQo.setReviewerUid(null);
                FdStatisticsType keyGroup = fdStatisticsApi.calculateKeyGroup(typeQo);
                if(keyGroup != null && keyGroup.getNum() > 0){
                    result.put("keyGroup", keyGroup.getNum());
                }else{
                    result.put("keyGroup", 0);
                }
                resultList.add(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        RetMsg retMsg = new RetMsg();
        iTotalRecords = page.getTotal();
        retMsg.put("data", resultList);
        retMsg.put("draw", draw);
        retMsg.put("recordsTotal", iTotalRecords);
        retMsg.put("recordsFiltered", iTotalRecords);
        return retMsg;
    }

    @RequestMapping(value = "listServantStreet", method = RequestMethod.GET)
    public String listServantStreet(Model model) {
        return "/medical/statistics/list_street_sign";
    }

    /*
     * 签约统计-街道
     */
    @RequestMapping(value = "listServantStreet", method = RequestMethod.POST)
    public @ResponseBody RetMsg listServantStreet(@RequestParam HashMap skey, @RequestParam(value = "draw", defaultValue = "1") Integer draw) {
        Long iTotalRecords;
        DataTableUtil.FormatOptions(skey);
        FdStatisticsGroupQo qo = DataTableUtil.fillQo(skey,FdStatisticsGroupQo.class);
        draw += 1;
        PageInfo<FdStatisticsGroup> page = fdStatisticsApi.calculateStreetGroup(qo);
        List<FdStatisticsGroup> groupList = page.getList();
        List<HashMap> resultList = new ArrayList<>();
        //基数时间
        String baseTime = DateUtil.dateFormate(new Date(), "yyyy-MM");
        try {
            if(skey.containsKey("baseTime") && skey.get("baseTime") != null){
                baseTime = String.valueOf(skey.get("baseTime"));
            }else{
                List<String> list = fdStatisticBaseApi.findTimes(null);
                if(list != null && list.size() > 0){
                    baseTime = list.get(0);
                }
            }
            FdStatisticsTypeQo typeQo = PojoUtil.convert(qo, FdStatisticsTypeQo.class);
            typeQo.setTeamId(null);
            typeQo.setReviewerUid(null);
            for(FdStatisticsGroup group : groupList){
                HashMap result = new HashMap();
                result.put("streetId", group.getStreetId());
                result.put("streetName", group.getStreetName());
                result.put("teamNum", group.getTeamNum());
                int noKeyGroup = 0;
                //遍历type
                for(FdStatisticsType type : group.getTypeNum()) {
                    result.put(ResidentTypeEnum.getNameByType(type.getType()), type.getNum());
                    if("10".equals(type.getType())){
                        noKeyGroup += type.getNum();
                    }
                }
                //重点人群
                int keyGroup = 0;
                typeQo.setStreetId(group.getStreetId());
                FdStatisticsType keyGroupType = fdStatisticsApi.calculateKeyGroup(typeQo);
                if(keyGroupType != null && keyGroupType.getNum() > 0){
                    keyGroup += keyGroupType.getNum();
                    result.put("keyGroup", keyGroupType.getNum());
                }else{
                    result.put("keyGroup", 0);
                }
                //查询基数获取签约率
                if(group.getStreetId() != null && group.getStreetId() > 0){
                    getStatisticsBase(result, baseTime, noKeyGroup, keyGroup, group.getStreetId());
                }

                resultList.add(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        RetMsg retMsg = new RetMsg();
        iTotalRecords = page.getTotal();
        retMsg.put("data", resultList);
        retMsg.put("draw", draw);
        retMsg.put("recordsTotal", iTotalRecords);
        retMsg.put("recordsFiltered", iTotalRecords);
        return retMsg;
    }

    @RequestMapping(value = "listServantTeam", method = RequestMethod.GET)
    public String listServantTeam(Model model,Integer streetId) {
        model.addAttribute("streetId",streetId);
        return "/medical/statistics/list_team_sign";
    }

    /*
     * 签约统计-团队
     */
    @RequestMapping(value = "listServantTeam", method = RequestMethod.POST)
    public @ResponseBody RetMsg listServantTeam(@RequestParam HashMap skey, @RequestParam(value = "draw", defaultValue = "1") Integer draw) {
        Long iTotalRecords;
        DataTableUtil.FormatOptions(skey);
        FdStatisticsGroupQo qo = DataTableUtil.fillQo(skey,FdStatisticsGroupQo.class);
        draw += 1;
        PageInfo<FdStatisticsGroup> page = fdStatisticsApi.calculateTeamGroup(qo);
        List<FdStatisticsGroup> groupList = page.getList();
        List<HashMap> resultList = new ArrayList<>();
        try {
            for(FdStatisticsGroup group : groupList){
                HashMap result = new HashMap();
                result.put("streetId", qo.getStreetId());
                result.put("teamId", group.getTeamId());
                result.put("teamName", group.getTeamName());
                for(FdStatisticsType type : group.getTypeNum()) {
                    result.put(ResidentTypeEnum.getNameByType(type.getType()), type.getNum());
                }
                //重点人群
                FdStatisticsTypeQo typeQo = PojoUtil.convert(qo, FdStatisticsTypeQo.class);
                typeQo.setStreetId(null);
                typeQo.setTeamId(group.getTeamId());
                typeQo.setReviewerUid(null);
                FdStatisticsType keyGroup = fdStatisticsApi.calculateKeyGroup(typeQo);
                if(keyGroup != null && keyGroup.getNum() > 0){
                    result.put("keyGroup", keyGroup.getNum());
                }else{
                    result.put("keyGroup", 0);
                }
                resultList.add(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        RetMsg retMsg = new RetMsg();
        iTotalRecords = page.getTotal();
        //retMsg.put("response", new Response(0));
        retMsg.put("data", resultList);
        retMsg.put("draw", draw);
        retMsg.put("recordsTotal", iTotalRecords);
        retMsg.put("recordsFiltered", iTotalRecords);
        return retMsg;
    }


    @RequestMapping(value = "listServantMember", method = RequestMethod.GET)
    public String listServantMember(Model model,Integer teamId,Integer streetId) {
        model.addAttribute("streetId",streetId);
        model.addAttribute("teamId",teamId);
        return "/medical/statistics/list_member_sign";
    }

    @RequestMapping(value = "listServantMember", method = RequestMethod.POST)
    public @ResponseBody RetMsg listServantMember(@RequestParam HashMap skey, @RequestParam(value = "draw", defaultValue = "1") Integer draw) {
        Long iTotalRecords;
        DataTableUtil.FormatOptions(skey);
        FdStatisticsGroupQo qo = DataTableUtil.fillQo(skey,FdStatisticsGroupQo.class);
        draw += 1;
        PageInfo<FdStatisticsGroup> page = fdStatisticsApi.calculateMemberGroup(qo);
        List<FdStatisticsGroup> groupList = page.getList();
        List<HashMap> resultList = new ArrayList<>();
        try {
            for(FdStatisticsGroup group : groupList){
                HashMap result = new HashMap();
                result.put("memberName", group.getServantName());

                for(FdStatisticsType type : group.getTypeNum()) {
                    result.put(ResidentTypeEnum.getNameByType(type.getType()), type.getNum());

                }
                //重点人群
                FdStatisticsTypeQo typeQo = PojoUtil.convert(qo, FdStatisticsTypeQo.class);
                typeQo.setStreetId(null);
                typeQo.setReviewerUid(group.getServantUid());
                FdStatisticsType keyGroup = fdStatisticsApi.calculateKeyGroup(typeQo);
                if(keyGroup != null && keyGroup.getNum() > 0){
                    result.put("keyGroup", keyGroup.getNum());
                }else{
                    result.put("keyGroup", 0);
                }
                resultList.add(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        RetMsg retMsg = new RetMsg();
        iTotalRecords = page.getTotal();
        //retMsg.put("response", new Response(0));
        retMsg.put("data", resultList);
        retMsg.put("draw", draw);
        retMsg.put("recordsTotal", iTotalRecords);
        retMsg.put("recordsFiltered", iTotalRecords);
        return retMsg;
    }


    @RequestMapping(value="downExcel")
    @ResponseBody
    public RetMsg downExcel(FdStatisticsGroupQo qo,String baseTime, String headers, HttpServletRequest request){
        RetMsg regMsg = new RetMsg();
        String[] headerArr = headers.split(",");
        //获取数据
        qo.setPageNo(1L);
        qo.setPageSize(20000L);
        PageInfo<FdStatisticsGroup> page = new PageInfo<>();
        if(qo.getRegionId() != null && qo.getRegionId() > 0){
            page = fdStatisticsApi.calculateStreetGroup(qo);
        }else if(qo.getStreetId() != null && qo.getStreetId() > 0){
            page = fdStatisticsApi.calculateTeamGroup(qo);
        }else if(qo.getTeamId() != null && qo.getTeamId() > 0){
            page = fdStatisticsApi.calculateMemberGroup(qo);
        }
        List<FdStatisticsGroup> groupList = page.getList();
        if(groupList.size() == 0){
            regMsg.put("code", -1);
            regMsg.put("msg", "查询为空");
            return regMsg;
        }
        List<HashMap> resultList = new ArrayList<>();
        //区分不同页面header不同
        Byte cellType = 0;
        if(qo.getSignTab() == 1 && qo.getRegionId() != null && qo.getRegionId() > 0){
            cellType = 1;
        }else if(qo.getSignTab() == 2 && qo.getRegionId() != null && qo.getRegionId() > 0){
            cellType = 2;
        }else if(qo.getSignTab() == 2){
            cellType = 3;
        }
        try {
            for(FdStatisticsGroup group : groupList){
                HashMap result = new HashMap();
                FdStatisticsTypeQo typeQo = PojoUtil.convert(qo, FdStatisticsTypeQo.class);
                if(StringUtils.isNotBlank(group.getStreetName()) && group.getStreetId() != null && group.getStreetId() > 0){
                    result.put("streetName", group.getStreetName());
                    typeQo.setStreetId(group.getStreetId());
                    typeQo.setTeamId(null);
                    typeQo.setReviewerUid(null);
                }
                if(StringUtils.isNotBlank(group.getTeamName()) && group.getTeamId() != null && group.getTeamId() > 0){
                    result.put("teamName", group.getTeamName());
                    typeQo.setTeamId(group.getTeamId());
                    typeQo.setStreetId(null);
                    typeQo.setReviewerUid(null);
                }
                if(StringUtils.isNotBlank(group.getServantName()) && group.getServantUid() != null && group.getServantUid() > 0){
                    result.put("memberName", group.getServantName());
                    typeQo.setReviewerUid(group.getServantUid());
                    typeQo.setStreetId(null);
                }
                if(group.getTeamNum() != null && group.getTeamNum() > 0)
                    result.put("teamNum", group.getTeamNum());
                //重点人群
                FdStatisticsType keyGroupType = fdStatisticsApi.calculateKeyGroup(typeQo);
                int keyGroup = 0;
                if(keyGroupType != null && keyGroupType.getNum() > 0){
                    keyGroup += keyGroupType.getNum();
                    result.put("keyGroup", keyGroupType.getNum());
                }else{
                    result.put("keyGroup", 0);
                }
                //各人群分类
                int noKeyGroup = 0;
                for(FdStatisticsType type : group.getTypeNum()) {
                    result.put(ResidentTypeEnum.getNameByType(type.getType()), type.getNum());
                    if("10".equals(type.getType())){
                        noKeyGroup += type.getNum();
                    }
                }
                //查询基数
                if(group.getStreetId() != null && group.getStreetId() > 0){
                    getStatisticsBase(result, baseTime, noKeyGroup, keyGroup, group.getStreetId());
                }
                resultList.add(result);
            }
            //生成excel并导出
            String fileName = "签约统计.xls"; //模板名称
            String pathurl = request.getServletContext().getRealPath("")+"download/";
            File files = ExcelUtils.outputExcelTemplate(pathurl + fileName, headerArr, null, null, resultList, cellType);
            regMsg.put("path" , request.getScheme() +"://" + request.getServerName()
                    + ":" +request.getServerPort()
                    + "/download/"
                    + fileName);
            regMsg.put("code" , 0);
        } catch (Exception e) {
            e.printStackTrace();
            regMsg.put("code" , -1);
        }
        return regMsg;

    }



    @RequestMapping(value = "getBaseTime", method = RequestMethod.POST)
    @ResponseBody
    public RetMsg getRecentBaseTime() {
        RetMsg retMsg = new RetMsg();
        List<String> baseTimeList = fdStatisticBaseApi.findTimes(null);
        retMsg.put("baseTimeList", baseTimeList);
        return retMsg;
    }
    /** 获取统计基数 **/
    private HashMap getStatisticsBase(HashMap result, String baseTime, int noKeyGroup, int keyGroup, int streetId){
        FdStatisticBaseQo baseQo = new FdStatisticBaseQo();
        if(StringUtils.isNotBlank(baseTime)){
            String[] timeArr = baseTime.split("-");
            baseQo.setYear(Integer.valueOf(timeArr[0]));
            baseQo.setMonth(Integer.valueOf(timeArr[1]));
        }
        baseQo.setRegionId(streetId);
        //重点人群基数
        int keyGroupBase = 0;
        baseQo.setType(ResidentTypeEnum.keyGroup.getType());
        List<FdStatisticBase> keyBaseList = fdStatisticBaseApi.list(baseQo);
        if (Collections3.isNotEmpty(keyBaseList)) {
            keyGroupBase = keyBaseList.get(0).getValue();
        }
        //非重点人群基数
        int noKeyGroupBase = 0;
        baseQo.setType(ResidentTypeEnum.noKeyGroup.getType());
        List<FdStatisticBase> noKeyBaseList = fdStatisticBaseApi.list(baseQo);
        if (Collections3.isNotEmpty(noKeyBaseList)) {
            noKeyGroupBase = noKeyBaseList.get(0).getValue();
        }
        DecimalFormat df = new DecimalFormat("0.00");
        if(noKeyGroupBase > 0){
            result.put("noKeyGroupRate", df.format(((float)noKeyGroup/noKeyGroupBase)*100));
        }else{
            result.put("noKeyGroupRate", "0.00");
        }
        if(keyGroupBase > 0){
            result.put("keyGroupRate", df.format(((float)keyGroup/keyGroupBase)*100));
        }else{
            result.put("keyGroupRate", "0.00");
        }
        if((noKeyGroupBase+keyGroupBase) > 0){
            result.put("permanentGroupRate", df.format(((float)(noKeyGroup+keyGroup)/(noKeyGroupBase+keyGroupBase))*100));
        }else{
            result.put("permanentGroupRate", "0.00");
        }
        return result;
    }












    /**
     * 基数维护
     *
     */

    @RequestMapping(value = "listBase", method = RequestMethod.GET)
    public String listBase(Model model) {
        return "/medical/statistics/list_base";
    }

    @RequestMapping(value = "listBase", method = RequestMethod.POST)
    public @ResponseBody
    RetMsg listArea(@RequestParam HashMap skey, @RequestParam(value = "draw", defaultValue = "1") Integer draw) {
        List<BasRegion> regions = getRegions();
        String year = String.valueOf(skey.get("year"));
        String month = String.valueOf(skey.get("month"));
        List<FdStatisticBaseVo> list = getResult(Integer.valueOf(year), Integer.valueOf(month), regions);

        RetMsg retMsg = new RetMsg();
        retMsg.put("data", list);
        retMsg.put("recordsTotal", list.size());
        retMsg.put("draw", draw);
        retMsg.put("recordsFiltered", list.size());
        return retMsg;
    }

    private List<BasRegion> getRegions() {
        BasRegionQo basRegionQo = new BasRegionQo();
        basRegionQo.setPid(404345);
        basRegionQo.setSortway("sort asc");
        basRegionQo.setCodeNot("40");
        List<BasRegion> regions = basRegionApi.list(basRegionQo);
        return regions;
    }

    @RequestMapping(value = "findTimes", method = RequestMethod.POST)
    public @ResponseBody
    RetMsg findTimes(Integer regionId, Model model) {
        RetMsg retMsg = new RetMsg();
        List<String> list = fdStatisticBaseApi.findTimes(null);
        retMsg.put("timeList", list);
        return retMsg;
    }

    @RequestMapping(value = "edit", method = RequestMethod.GET)
    public
    String edit(String regionId,String year,String month, Model model) {
       /* Object y = skey.get("year");
        Object m = skey.get("month");
        Object r = skey.get("regionId");*/
        FdStatisticBaseVo vo = new FdStatisticBaseVo();
        String y = year;
        String m = month;
        String r = regionId;

        if (y != null && m != null && r != null) {
            /*String year = String.valueOf(y);
            String month = String.valueOf(m);
            String regionId = String.valueOf(r);*/

            BasRegion region = basRegionApi.get(Integer.valueOf(regionId));
            List<FdStatisticBaseVo> list = getResult(Integer.valueOf(year), Integer.valueOf(month), region);
            vo = list.get(0);
            vo.setYm(year + "-" + month);
            model.addAttribute("regionId",regionId);
        } else {// 新建
            Date date = new Date();
            String dateStr = DateUtil.dateFormate(date, "yyyy-MM");
            String[] arr = dateStr.split("-");
            vo.setRegion("新建基数");
            vo.setYm(arr[0] + "-" + arr[1]);
            model.addAttribute("add",true);
        }
        model.addAttribute("statisticBase",vo);
        List<BasRegion> regions = getRegions();
        model.addAttribute("regions",regions);
        return "/medical/statistics/edit_base";
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public RetMsg save(FdStatisticBaseVo vo) {
        try {
            String ym = vo.getYm();
            String[] arr = ym.split("-");

            FdStatisticBase bean = new FdStatisticBase();
            bean.setYear(Integer.valueOf(arr[0]));
            bean.setMonth(Integer.valueOf(arr[1]));
            bean.setRegionId(vo.getRegionId());
            BasRegion region = basRegionApi.get(vo.getRegionId());
            bean.setRegion(region.getTitle());
            bean.setRegionLevel(region.getLevel());

            FdStatisticBaseQo qo = new FdStatisticBaseQo();
            qo.setYear(Integer.valueOf(arr[0]));
            qo.setMonth(Integer.valueOf(arr[1]));
            qo.setRegionId(vo.getRegionId());
            this.saveBean(vo, qo, bean);
        } catch(ErrorCodeException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return RetMsg.failed();
        }
        return RetMsg.success();
    }

    private List<FdStatisticBaseVo> getResult(int year, int month, BasRegion region) {
        List<BasRegion> regions = Lists.newArrayList();
        regions.add(region);
        return getResult(year, month, regions);
    }

    private List<FdStatisticBaseVo> getResult(int year, int month, List<BasRegion> regions) {
        List<FdStatisticBaseVo> result = Lists.newArrayList();
        if (Collections3.isEmpty(regions)) {
            return result;
        }

        FdStatisticBaseQo qo = new FdStatisticBaseQo();
        qo.setYear(year);
        qo.setMonth(month);

        for (BasRegion region: regions) {
            qo.setRegionId(region.getId());
            List<FdStatisticBase> li = fdStatisticBaseApi.list(qo);

            FdStatisticBaseVo vo = new FdStatisticBaseVo();
            vo.setRegion(region.getTitle());
            vo.setRegionId(region.getId());

            if (Collections3.isEmpty(li)) {
                result.add(vo);
                continue;
            }

//			int total = 0;
            for (FdStatisticBase statisticBase: li) {
                String type = statisticBase.getType();

                switch (type) {
                    case "99":
                        vo.setKeyGroup(statisticBase.getValue());
                        break;
                    case "01":
                        vo.setTypeYcf(statisticBase.getValue());
                        break;
                    case "02":
                        vo.setTypeEt(statisticBase.getValue());
                        break;
                    case "03":
                        vo.setTypeLnr(statisticBase.getValue());
                        break;
                    case "04":
                        vo.setTypeGxy(statisticBase.getValue());
                        break;
                    case "05":
                        vo.setTypeTnb(statisticBase.getValue());
                        break;
                    case "06":
                        vo.setTypeJsb(statisticBase.getValue());
                        break;
                    case "07":
                        vo.setTypeFjh(statisticBase.getValue());
                        break;
                    case "08":
                        vo.setTypeCjr(statisticBase.getValue());
                        break;
                    case "09":
                        vo.setTypeTs(statisticBase.getValue());
                        break;
                    case "10":
                        vo.setTypeFzd(statisticBase.getValue());
                        break;
                    case "11":
                        vo.setTypeDsr(statisticBase.getValue());
                        break;
                    case "12":
                        vo.setTypeCzdb(statisticBase.getValue());
                        break;
                    default:
                        break;
                }
//				total += (statisticBase.getValue() != null ? statisticBase.getValue() : 0);
            }
            vo.setCzrks((vo.getKeyGroup() != null ?vo.getKeyGroup():0) + (vo.getTypeFzd() != null ?vo.getTypeFzd():0));
            result.add(vo);
        }
        return result;
    }

    private void saveBean(FdStatisticBaseVo vo, FdStatisticBaseQo qo, FdStatisticBase bean) {
        if (Utils.isNotEmpty(vo.getKeyGroup())) {
            qo.setType("99");
            List<FdStatisticBase> li = fdStatisticBaseApi.list(qo);
            if (Collections3.isEmpty(li)) {
                bean.setType("99");
                bean.setValue(vo.getKeyGroup());
                fdStatisticBaseApi.save(bean);
            } else {
                FdStatisticBase beanUp = li.get(0);
                beanUp.setValue(vo.getKeyGroup());
                fdStatisticBaseApi.update(beanUp);
            }
        }

        if (Utils.isNotEmpty(vo.getTypeYcf())) {
            qo.setType("01");
            List<FdStatisticBase> li = fdStatisticBaseApi.list(qo);
            if (Collections3.isEmpty(li)) {
                bean.setType("01");
                bean.setValue(vo.getTypeYcf());
                fdStatisticBaseApi.save(bean);
            } else {
                FdStatisticBase beanUp = li.get(0);
                beanUp.setValue(vo.getTypeYcf());
                fdStatisticBaseApi.update(beanUp);
            }
        }

        if (Utils.isNotEmpty(vo.getTypeEt())) {
            qo.setType("02");
            List<FdStatisticBase> li = fdStatisticBaseApi.list(qo);
            if (Collections3.isEmpty(li)) {
                bean.setType("02");
                bean.setValue(vo.getTypeEt());
                fdStatisticBaseApi.save(bean);
            } else {
                FdStatisticBase beanUp = li.get(0);
                beanUp.setValue(vo.getTypeEt());
                fdStatisticBaseApi.update(beanUp);
            }
        }

        if (Utils.isNotEmpty(vo.getTypeLnr())) {
            qo.setType("03");
            List<FdStatisticBase> li = fdStatisticBaseApi.list(qo);
            if (Collections3.isEmpty(li)) {
                bean.setType("03");
                bean.setValue(vo.getTypeLnr());
                fdStatisticBaseApi.save(bean);
            } else {
                FdStatisticBase beanUp = li.get(0);
                beanUp.setValue(vo.getTypeLnr());
                fdStatisticBaseApi.update(beanUp);
            }
        }

        if (Utils.isNotEmpty(vo.getTypeGxy())) {
            qo.setType("04");
            List<FdStatisticBase> li = fdStatisticBaseApi.list(qo);
            if (Collections3.isEmpty(li)) {
                bean.setType("04");
                bean.setValue(vo.getTypeGxy());
                fdStatisticBaseApi.save(bean);
            } else {
                FdStatisticBase beanUp = li.get(0);
                beanUp.setValue(vo.getTypeGxy());
                fdStatisticBaseApi.update(beanUp);
            }
        }

        if (Utils.isNotEmpty(vo.getTypeTnb())) {
            qo.setType("05");
            List<FdStatisticBase> li = fdStatisticBaseApi.list(qo);
            if (Collections3.isEmpty(li)) {
                bean.setType("05");
                bean.setValue(vo.getTypeTnb());
                fdStatisticBaseApi.save(bean);
            } else {
                FdStatisticBase beanUp = li.get(0);
                beanUp.setValue(vo.getTypeTnb());
                fdStatisticBaseApi.update(beanUp);
            }
        }

        if (Utils.isNotEmpty(vo.getTypeJsb())) {
            qo.setType("06");
            List<FdStatisticBase> li = fdStatisticBaseApi.list(qo);
            if (Collections3.isEmpty(li)) {
                bean.setType("06");
                bean.setValue(vo.getTypeJsb());
                fdStatisticBaseApi.save(bean);
            } else {
                FdStatisticBase beanUp = li.get(0);
                beanUp.setValue(vo.getTypeJsb());
                fdStatisticBaseApi.update(beanUp);
            }
        }

        if (Utils.isNotEmpty(vo.getTypeFjh())) {
            qo.setType("07");
            List<FdStatisticBase> li = fdStatisticBaseApi.list(qo);
            if (Collections3.isEmpty(li)) {
                bean.setType("07");
                bean.setValue(vo.getTypeFjh());
                fdStatisticBaseApi.save(bean);
            } else {
                FdStatisticBase beanUp = li.get(0);
                beanUp.setValue(vo.getTypeFjh());
                fdStatisticBaseApi.update(beanUp);
            }
        }

        if (Utils.isNotEmpty(vo.getTypeCjr())) {
            qo.setType("08");
            List<FdStatisticBase> li = fdStatisticBaseApi.list(qo);
            if (Collections3.isEmpty(li)) {
                bean.setType("08");
                bean.setValue(vo.getTypeCjr());
                fdStatisticBaseApi.save(bean);
            } else {
                FdStatisticBase beanUp = li.get(0);
                beanUp.setValue(vo.getTypeCjr());
                fdStatisticBaseApi.update(beanUp);
            }
        }

        if (Utils.isNotEmpty(vo.getTypeTs())) {
            qo.setType("09");
            List<FdStatisticBase> li = fdStatisticBaseApi.list(qo);
            if (Collections3.isEmpty(li)) {
                bean.setType("09");
                bean.setValue(vo.getTypeTs());
                fdStatisticBaseApi.save(bean);
            } else {
                FdStatisticBase beanUp = li.get(0);
                beanUp.setValue(vo.getTypeTs());
                fdStatisticBaseApi.update(beanUp);
            }
        }

        if (Utils.isNotEmpty(vo.getTypeFzd())) {
            qo.setType("10");
            List<FdStatisticBase> li = fdStatisticBaseApi.list(qo);
            if (Collections3.isEmpty(li)) {
                bean.setType("10");
                bean.setValue(vo.getTypeFzd());
                fdStatisticBaseApi.save(bean);
            } else {
                FdStatisticBase beanUp = li.get(0);
                beanUp.setValue(vo.getTypeFzd());
                fdStatisticBaseApi.update(beanUp);
            }
        }

        if (Utils.isNotEmpty(vo.getTypeDsr())) {
            qo.setType("11");
            List<FdStatisticBase> li = fdStatisticBaseApi.list(qo);
            if (Collections3.isEmpty(li)) {
                bean.setType("11");
                bean.setValue(vo.getTypeDsr());
                fdStatisticBaseApi.save(bean);
            } else {
                FdStatisticBase beanUp = li.get(0);
                beanUp.setValue(vo.getTypeDsr());
                fdStatisticBaseApi.update(beanUp);
            }
        }

        if (Utils.isNotEmpty(vo.getTypeCzdb())) {
            qo.setType("12");
            List<FdStatisticBase> li = fdStatisticBaseApi.list(qo);
            if (Collections3.isEmpty(li)) {
                bean.setType("12");
                bean.setValue(vo.getTypeCzdb());
                fdStatisticBaseApi.save(bean);
            } else {
                FdStatisticBase beanUp = li.get(0);
                beanUp.setValue(vo.getTypeCzdb());
                fdStatisticBaseApi.update(beanUp);
            }
        }
    }






}
